package cn.wind.xboot.module.web.controller.systool;

import cn.hutool.core.convert.Convert;
import cn.wind.xboot.core.annotation.RestJsonController;
import cn.wind.xboot.core.res.ApiResult;
import cn.wind.xboot.logic.tools.entity.TableInfo;
import cn.wind.xboot.logic.tools.service.IGenService;
import cn.wind.xboot.framework.domain.PageVo;
import cn.wind.xboot.framework.domain.SearchVo;
import cn.wind.xboot.framework.web.controller.BaseController;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.common.collect.Maps;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * 代码生成 操作处理
 * 
 * @author ruoyi
 */
@RestJsonController
@RequestMapping(value = "/tool/sqlcode")
public class GenController extends BaseController<TableInfo,Long>{

    @Autowired
    private IGenService genService;

    @GetMapping
    public ApiResult get(TableInfo tableInfo, PageVo pageVo, SearchVo searchVo) {
        Map<String,Object> map=Maps.newHashMap();
        if(searchVo.getStartDate()!=null){
            map.put("beginTime",searchVo.getStartDate());
        }
        if(searchVo.getEndDate()!=null){
            map.put("endTime",searchVo.getEndDate());
        }
        tableInfo.setParams(map);
        IPage page=genService.page(pageVo.init(),tableInfo);
        return ApiResult.Custom().success().add(page);
    }

    /**
     * 生成代码
     */
    @GetMapping("/genCode/{tableName}")
    public void genCode(HttpServletResponse response, @PathVariable("tableName") String tableName) throws IOException
    {
        byte[] data = genService.generatorCode(tableName);
        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=\""+System.currentTimeMillis()+".zip\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");

        IOUtils.write(data, response.getOutputStream());
    }

    /**
     * 批量生成代码
     */
    @GetMapping("/batchGenCode")
    public void batchGenCode(HttpServletResponse response, String tables, HttpServletRequest request) throws IOException
    {
        String[] tableNames = Convert.toStrArray(tables);
        byte[] data = genService.generatorCode(tableNames);
        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=\""+System.currentTimeMillis()+".zip\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");

        IOUtils.write(data, response.getOutputStream());
    }
}
